﻿using LD.Host;
using LD.Host.Mes;
using LD.Host.项目;
using LD.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace LD.Tool
{
    [Tool(Text = "WebService", FrmParam = "ToolWebServiceFrm", ToolType = ToolEnum.通讯)]
    public class ToolWebService : BaseTool
    {
        public override OpResult Execute(TB_Tool model)
        {
            try
            {
                isSuccess = false;
                stopwatch.Start();
                if (model.Param != null)
                {
                    var parm = Newtonsoft.Json.JsonConvert.DeserializeObject<WebServiceParam>(model.Param);
                    if (parm.Datas.Count > 0
                        && !string.IsNullOrEmpty(parm.Url)
                        && !string.IsNullOrEmpty(parm.InterFace))
                    {
                        Hashtable hashtable = new Hashtable();
                        foreach (string item in parm.Datas.Keys)
                        {
                            string val = Cache.GetVar<string>(parm.Datas[item].ToString());
                            hashtable.Add(item, val);
                        }
                        isSuccess = MesByHYFSK.Check(parm.Url, parm.InterFace, hashtable);
                    }
                    else
                        Log(model, "参数不完整", LogLevel.警告);

                    if (!isSuccess)
                        EchoPLC(model.EchoPLC);

                    PubSub.Hub.Default.PublishAsync(new KazamHandle()
                    {
                        kazamState = KazamState.Start,
                        message = isSuccess ? $"MES OK" : "MES检查失败",
                        Slot = "Slot" + parm.Tag
                    });
                }
            }
            catch (Exception ex)
            {
                Log(model, ex.Message, LogLevel.严重);
            }
            finally
            {
                stopwatch.Stop();
            }
            return new OpResult() { IsSuccess = isSuccess, Message = message, ExecuteTime = stopwatch.ElapsedMilliseconds };

        }
    }
}
